package com.example.yls.demoa;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * Created by yls on 2018/11/6.
 */

public class NetReceiver extends BroadcastReceiver {

    private ConnectivityManager mConnectivityManager;

    private NetworkInfo netInfo;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

            mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = mConnectivityManager.getActiveNetworkInfo();
            if(netInfo != null && netInfo.isAvailable()) {
                //网络连接
                String name = netInfo.getTypeName();
                if(netInfo.getType()==ConnectivityManager.TYPE_WIFI){
                    //WiFi网络
                    Toast.makeText(context,"当前使用WIFI",Toast.LENGTH_LONG).show();
                }else if(netInfo.getType()==ConnectivityManager.TYPE_ETHERNET){
                    //有线网络
                    Toast.makeText(context,"当前使用有线网络",Toast.LENGTH_LONG).show();
                }else if(netInfo.getType()==ConnectivityManager.TYPE_MOBILE){
                    //3g网络
                    Toast.makeText(context,"当前使用流量数据网络",Toast.LENGTH_LONG).show();
                }
            } else {
                //网络断开
                Toast.makeText(context,"当前网络断开",Toast.LENGTH_LONG).show();
            }
        }
    }
}
